//
//  ZJRefreshControl.swift
//  sinaWeibo
//
//  Created by liii on 16/8/4.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit

// 下拉刷新的三种状态
enum ZJRefreshStatus: Int {
    case Normal = 0         // 默认状态
    case Pulling = 1        // 下拉到临界值, 等待刷新
    case Refreshing = 2     // 正在刷新
}

let refreshHeight: CGFloat = 60

class ZJRefreshControl: UIControl {
    
    // 捕捉状态
    var refreshState: ZJRefreshStatus = .Normal {
        didSet {
            switch refreshState {
            case .Normal:
                print("下拉刷新")
                tipLabel.text = "下拉刷新"
                
                // 停止菊花转动
                indicationView.stopAnimating()
                // 显示箭头
                arrowIcon.hidden = false
                // 恢复箭头方向
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 恢复默认值
                    self.arrowIcon.transform = CGAffineTransformIdentity
                    
                    if oldValue == .Refreshing {
                        // 让contentInset.top上移
                        var inset = self.scrollView!.contentInset
                        inset.top -= refreshHeight
                        self.scrollView?.contentInset = inset
                    }
                })
            case .Pulling:
                print("松手刷新")
                tipLabel.text = "松手刷新"
                
                // 改变箭头方向
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 旋转180°
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                print("正在刷新")
                tipLabel.text = "正在刷新"
                
                // 隐藏箭头
                arrowIcon.hidden = true
                // 转动菊花
                indicationView.startAnimating()
                // 触发监听事件
                self.sendActionsForControlEvents(.ValueChanged)
                
                // 让content下移
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 恢复默认值
                    self.arrowIcon.transform = CGAffineTransformIdentity
                    
                    // 让contentInset.top上移
                    var inset = self.scrollView!.contentInset
                    inset.top += refreshHeight
                    self.scrollView?.contentInset = inset
                })
            }
        }
    }

    override init(frame: CGRect) {
        // 自定义控件尺寸
        let rect = CGRectMake(0, -refreshHeight, screenWidth, refreshHeight)
        super.init(frame: rect)
        
        backgroundColor = UIColor.greenColor()
        // 搭建UI界面
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // UIView的声明周期方法: 将要被添加到父视图的时候会被调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        if let fatherView = newSuperview as? UIScrollView {
            // 保存父视图
            scrollView = fatherView
            
            // KVO: 添加观察者
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    // KVO: 移除监听者
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // KVO: 处理监听
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

        // 偏移量
        let offsetY = scrollView?.contentOffset.y ?? 0
        // 临界值
        let conditionValue = -(refreshHeight + (scrollView?.contentInset.top ?? 0))
        // 保证每种状态只触发一次
        if scrollView!.dragging {
            if refreshState == .Pulling && offsetY > conditionValue {
                refreshState = .Normal
            } else if refreshState == .Normal && offsetY < conditionValue {
                refreshState = .Pulling
            }
        } else {
            if refreshState == .Pulling {
                refreshState = .Refreshing
            }
        }
    }
    
    // 更新完毕之后, 恢复状态
    func endRefreshing() {
        // gcd延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            // 恢复状态
            self.refreshState = .Normal
        })
    }
    
    private func setupUI() {
        
        addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicationView)
        
        backImageView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
        }
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.centerY.equalTo(self)
        }
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left)
            make.centerY.equalTo(tipLabel)
        }
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
    }
    
    // 文字
    private lazy var tipLabel: UILabel = UIFactory.labelWithText("下拉刷新", fontSize: 14, textColor: UIColor.redColor())
    // 箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 菊花
    private lazy var indicationView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    // 背景图片
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    // 用于保存父视图
    private var scrollView: UIScrollView?
}
